package com.red.wine;

import java.io.File;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.MKEvent;
import com.red.wine.sql.SqlHelper;
import com.red.wine.sql.UserLog;
import com.red.wine.util.StringUtil;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.Toast;

public class WineApp extends Application {
	private Activity currentActivity;
	private static String sdkVersion;
	private static WineApp instance;
	private boolean isExited;
	private static SqlHelper sqlHelper;
	/**
	 * @param sqlHelper 设置目标数据库
	 */
	public void setSqlHelper(SqlHelper sqlHelper) {
		WineApp.sqlHelper = sqlHelper;
	}

	/**
	 * @return 返回数据库对象
	 */
	public SqlHelper getSqlHelper() {
		return sqlHelper;
	}

	public void setExited(boolean isExited) {
		this.isExited = isExited;
	}

	public boolean isExited() {
		return isExited;
	}

	public synchronized static WineApp getInstance() {
		if (instance == null) {
			instance = new WineApp();
		}
		return instance;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		UserLog.getInstance().createFile();
		setSqlHelper(new SqlHelper(this, "wine", null,
				SqlHelper.getDBVersion()));
		instance = this;
		initEngineManager(this);
	}

	/**百度地图api key是否正确*/
	public boolean m_bKeyRight = true;
	public BMapManager mBMapManager = null;
	public static final String strKey = "AAA88D2B68CFF47A6FFE02A42ED9DA0B14E2CAAE";
	/**百度地图初始化*/
	public void initEngineManager(Context context) {
        if (mBMapManager == null) {
            mBMapManager = new BMapManager(context);
        }

        if (!mBMapManager.init(strKey,new MyGeneralListener())) {
            Toast.makeText(WineApp.getInstance().getApplicationContext(), 
                    "BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
        }
	}
	
	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	public class MyGeneralListener implements MKGeneralListener {
	        
	    
	      public void onGetNetworkState(int iError) {
	          if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
	              Toast.makeText(WineApp.getInstance().getApplicationContext(), "网络异常！",
	                  Toast.LENGTH_LONG).show();
	          }
	          else if (iError == MKEvent.ERROR_NETWORK_DATA) {
	              Toast.makeText(WineApp.getInstance().getApplicationContext(), "输入正确的检索条件！",
	                      Toast.LENGTH_LONG).show();
	          }
	            // ...
	      }

	  
	      public void onGetPermissionState(int iError) {
	          if (iError ==  MKEvent.ERROR_PERMISSION_DENIED) {
	              //授权Key错误：
	              Toast.makeText(WineApp.getInstance().getApplicationContext(), 
	                      "地图授权错误！", Toast.LENGTH_LONG).show();
	              WineApp.getInstance().m_bKeyRight = false;
	          }
	      }
	  }
	
	/**
	 * 发起定位
	 * @return
	 */
	public LocationClient mLocationClient;
	public Boolean isLocation = false;
	public LocationClient getmLocationClient() {
		try{
			if (mLocationClient == null) {
				//LocationClientOption 用来设置定位方式，包括是否缓存，是否使用gps，时间间隔等
				mLocationClient = new LocationClient(this);
				//LocationClientOption 用来设置定位方式，包括是否缓存，是否使用gps，时间间隔等
				LocationClientOption option = new LocationClientOption();
				option.setOpenGps(true);  //设置使用GPS
				//设置网络优先级，首选GPS定位
				option.setPriority(LocationClientOption.GpsFirst); 
				option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02
				option.setPoiExtraInfo(false);
				option.setScanSpan(500);//定时定位，500毫秒
				
				mLocationClient.setLocOption(option);
	
				//DBLocaitonListener 获取定位结果 
				mLocationClient.registerLocationListener(new BDLocationListener() {
					 
					//DBLocation 定位结果的封面，包含坐标和错误码等信息
					public void onReceiveLocation(BDLocation ll) {
						if (ll != null) {
//							Log.e("aaa", "ddffd"+ll.getLatitude());
							//维度判断
							if (ll.getLatitude() > 0.0001) {
								WineApp.getInstance().setCurrentLocation(ll);//封装当前定位结果
								isLocation = true;
//								Log.i(TAG, "getmLocationClient 即将结束定位");
								mLocationClient.stop();// 结束定位
	
							}
						}
					}
	
					public void onReceivePoi(BDLocation arg0) {
						// TODO Auto-generated method stub
	
					}
	
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return mLocationClient;
	}
	private BDLocation currentLocation;
	public BDLocation getCurrentLocation() {
		return currentLocation;
	}

	public void setCurrentLocation(BDLocation currentLocation) {
		this.currentLocation = currentLocation;
	}
	public int getScreenWidth() {
		WindowManager windowManager = this.getCurrentActivity()
				.getWindowManager();
		DisplayMetrics metrics = new DisplayMetrics();
		windowManager.getDefaultDisplay().getMetrics(metrics);
		return metrics.widthPixels;
	}

	public int getScreenHeight() {
		WindowManager windowManager = this.getCurrentActivity()
				.getWindowManager();
		DisplayMetrics metrics = new DisplayMetrics();
		windowManager.getDefaultDisplay().getMetrics(metrics);
		return metrics.heightPixels;
	}

	public void setCurrentActivity(Activity currentActivity) {
		this.currentActivity = currentActivity;
	}

	public Activity getCurrentActivity() {
		return currentActivity;
	}

	public String getSdkVersion() {
		if (StringUtil.isEmptyOrNull(sdkVersion)) {
			sdkVersion = String.valueOf(Build.VERSION.SDK_INT);
		}
		return sdkVersion;
	}

	public String getFilePath() {
		String result = null;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			result = Environment.getExternalStorageDirectory()
					.getAbsolutePath().concat("/atsmart");
			File gggMarket = new File(Environment.getExternalStorageDirectory()
					.getAbsolutePath(), "atsmart");
			if (!gggMarket.exists()) {
				gggMarket.mkdir();
			}
		} else {
			result = WineApp.getInstance().getFilesDir().getAbsolutePath();
		}
		return result;
	}

	public boolean isWiFiActive() {
		WifiManager mWifiManager = (WifiManager) getInstance().getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
		int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
		if (mWifiManager.isWifiEnabled() && ipAddress != 0) {
			return true;
		} else {
			return false;
		}
	}

	public boolean isNetworkAvailable() {
		ConnectivityManager mgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] info = mgr.getAllNetworkInfo();
		if (info != null) {
			for (int i = 0; i < info.length; i++) {
				if (info[i].getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}

	public boolean isWifiAvailable(Context context) {
		ConnectivityManager mgr = (ConnectivityManager) context
				.getSystemService(Context.WIFI_SERVICE);
		NetworkInfo[] info = mgr.getAllNetworkInfo();
		if (info != null) {
			for (int i = 0; i < info.length; i++) {
				if (info[i].getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}
	/**
	 * @return 返回纬度
	 */
	public double getLat() {
		return getCurrentLocation() == null ? 0.0 : getCurrentLocation()
				.getLatitude();
	}

	/**
	 * @return 返回经度 
	 */
	public double getLon() {
		return getCurrentLocation() == null ? 0.0 : getCurrentLocation()
				.getLongitude();
	}
}
